<?php

namespace app\superadmin\controller;
use app\common\controller\SuperadminBase;
use app\superadmin\model\Order as Model;
use app\superadmin\model\User;
use think\Controller;

use think\Db;

use think\Request;

use think\Session;
use app\superadmin\model\OrderRefund;



class Order extends SuperadminBase

{



    public function index()
    {

        $stafflist = Db::table('yup_user')->where('is_staff',1)->select();

        $this->assign('stafflist', $stafflist);

        return $this->fetch();

    }



    //获取订单列表

    public function gList(Request $request)

    {

        //获取每页显示的条数

        $limit = $request->param('limit');

        //获取当前页数

        $page = $request->param('page');

        $keywords = $request->param('keywords');

        $create_time = $request->param('create_time');

        $status = $request->param('status');

        $staff_id = $request->param('staff_id');

        $where = [];

        if (!empty($status)) {
             
             $where['status'] = $status;
        }


        if (!empty($staff_id)) {
             
             $where['staff_id'] = $staff_id;
        }



        if (!empty($create_time)) {
             
             $where['create_time'] = ['between',explode(' - ', $create_time)];
        }


        $goodList = Model::with('userinfo')->with('serviceinfo')->with('staffinfo')->where('code|province|city|county|brand|model', 'like', '%' . $keywords . '%')->where($where)->order('create_time desc')->paginate($limit, false, ['page' => $page])->toArray();

        return json(['code' => 0, 'msg' => '', 'count' => $goodList['total'], 'data' => $goodList['data']]);

    }

    


    //分配员工
    public function edit()
    {   

        if(\request()->isPost()){

            $data  = input('post.');

             Model::where('id',$data['id'])->update(['staff_id'=>$data['staff_id']]);

             return json(['code'=>1, 'message'=>'分配成功']);


        }else{

            $id = input('id');

            $storeList = User::where('is_staff',1)->field(['id','name'=>'label'])->select();

            $this->assign('storeList', $storeList);

            $this->assign('id', $id);
            return $this->fetch();

        }
        
    }




    public function look(){

        $id       = input('id');

        $info = Model::with('userinfo')->with('serviceinfo')->with('staffinfo')->where('id',$id)->find();
       
        $this->assign('info', $info);

        return $this->fetch('order/look');

    }

    
    // 订单退款
    public function refund(){
        $order_id = request()->post('id');
        Db::startTrans();
        try{
            $order = Model::where('id', $order_id)->find();
            if(!$order) throw new \Exception("订单不存在.");
            if($order->status != 2 && $order->status != 3) throw new \Exception("订单状态不能退款.");
            if($order->refund_status > 0) throw new \Exception("订单已经退款或在退款中.");
            $exists = $order->refunds()->where('status', '>', '-1')->count();
            if($exists > 0){
                throw new \Exception("数据错误,请联系管理员.");
            }
            // 新增退款订单
            $order->refund_status = 10;
            $insert = [
                'sn'    =>   date('YmdHis').intval(microtime(true)),
                'amount'    =>  $order->deposit,
                'admin_id'  =>  session('adminid'),
                'status'    =>  0,
            ];
            $params = [
                'out_trade_no'  =>  $order->code,
                'out_refund_no' =>  $insert['sn'],
                'total_fee' =>  intval($insert['amount'] * 100),
                'refund_fee'    =>  intval($insert['amount'] * 100),
                'refund_desc'   =>  '定金退回',
                'notify_url'    =>  url('index/notify/refund','','',true),
            ];
            if(config('app_debug')){
                $insert['request'] = $params;
            }
            
            $order->refunds()->save($insert);
            $order->save();
            $pay = \We::WePayRefund([
                'appid' =>  'wx6b0bc166ece6d3ea',
                'mch_id'    =>  '1610714247',
                'mch_key'   =>  'nqfxiu9pomyjytkvctruv2o42r84g2ao',
                'ssl_key'   =>  '/www/wwwroot/wechat_mer_cert/apiclient_key.pem',
                'ssl_cer'   =>  '/www/wwwroot/wechat_mer_cert/apiclient_cert.pem',
            ]);
           
            $res = $pay->create($params);
            if(config('app_debug')){
                $refund_order = $order->refunds()->order('create_time desc')->find();
                $refund_order->response = $res;
                $refund_order->save();
            }
            Db::commit();
            return json(['code'=>0,'msg'=>'退款请求已提交']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
    }
}

